﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OnlineAuction.Entity;
using System.Data.SqlClient;
using OnlineAuction.Business;


namespace OnlineAuction.Ajax
{
    public partial class UpdateAuctionHistory : System.Web.UI.Page
    {
        private string connectString;
        private SqlDataReader reader;
        private string user = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            string res = "nck";
            if (Request.Cookies["UserInfo"] != null)
            {
                AuctionBO bo = new AuctionBO();
                connectString = bo.GetConnection();
                int aid = int.Parse(Request.QueryString["AuctionID"]);
                user = Request.Cookies["UserInfo"]["UserName"].ToString();
                string lBuyer = Request.QueryString["lBuyer"];
                string lPrice = Request.QueryString["lPrice"];
                //string user = "hieunt";
                //check user moneys
                string price = Request.QueryString["price"];
                SqlConnection conn = new SqlConnection(connectString);
                conn.Open();
                //get money
                double money = 0;
                string query = "select VirtualMoney from Users where UserName ='" + user + "'";
                SqlCommand cmd = new SqlCommand(query, conn);
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    money = Double.Parse(reader["VirtualMoney"].ToString());
                }
                conn.Close();
                conn.Open();
                double lbm = 0;
                query = "select VirtualMoney from Users where UserName ='" + lBuyer + "'";
                cmd = new SqlCommand(query, conn);
                reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    lbm = Double.Parse(reader["VirtualMoney"].ToString());
                }
                double nPrice = 0;
                try
                {
                    nPrice = Double.Parse(price);

                    conn.Close();
                    if (money < nPrice)
                    {
                        res = "not enough money";
                        //if (Request.Cookies["UserInfo"]["FaultTime"] == null)
                        //    Response.Cookies["UserInfo"]["FaultTime"] = DateTime.Now.ToString("MM/dd/yy hh:mm:ss");
                        int counter;
                        if (Request.Cookies["counter"] == null)
                            counter = 0;
                        else
                        {
                            counter = int.Parse(Request.Cookies["counter"].Value);
                        }
                        counter++;

                        Response.Cookies["counter"].Value = counter.ToString();
                        Response.Cookies["counter"].Expires = DateTime.Now.AddDays(1);

                        if (counter >= 10)
                        {
                            //delete user
                            OnlineAuction.Business.UserBO ubo = new Business.UserBO();
                            ubo.BanUser(user);

                            if (Request.Cookies["UserInfo"] != null)
                            {
                                HttpCookie myCookie = new HttpCookie("UserInfo");
                                myCookie.Expires = DateTime.Now.AddDays(-1d);
                                Response.Cookies.Add(myCookie);
                            }
                            if (Request.Cookies["counter"] != null)
                            {
                                HttpCookie myCookie = new HttpCookie("counter");
                                myCookie.Expires = DateTime.Now.AddDays(-1d);
                                Response.Cookies.Add(myCookie);
                            }
                            Response.Redirect("Home.aspx");
                        }
                    }
                    else
                    {
                        res = "ok";
                        if (Request.Cookies["counter"] != null)
                        {
                            HttpCookie myCookie = new HttpCookie("counter");
                            myCookie.Expires = DateTime.Now.AddDays(-1d);
                            Response.Cookies.Add(myCookie);
                        }
                        conn.Open();
                        //create transaction
                        cmd = conn.CreateCommand();
                        SqlTransaction transaction;
                        //start a local transaction
                        transaction = conn.BeginTransaction("Bid");
                        //assign transaction object
                        cmd.Connection = conn;
                        cmd.Transaction = transaction;
                        try
                        {
                            //subtract money
                            cmd.CommandText = "update Users set VirtualMoney ='" + (money - nPrice) + "' where UserName='" + user + "'";
                            cmd.ExecuteNonQuery();
                            //return money
                            cmd.CommandText = "update Users set VirtualMoney ='" + (lbm + Double.Parse(lPrice)) + "' where UserName='" + lBuyer + "'";
                            cmd.ExecuteNonQuery();
                            //insert new record
                            string now = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
                            cmd.CommandText = "insert into AuctionHistory(AuctionID,UserName,TimeAuction,Price) values(" + aid + ",'" + user + "','" + now + "'," + price + ")";

                            cmd.ExecuteNonQuery();
                            transaction.Commit();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
                            Console.WriteLine("  Message: {0}", ex.Message);

                            // Attempt to roll back the transaction. 
                            try
                            {
                                transaction.Rollback();
                            }
                            catch (Exception ex2)
                            {
                                // This catch block will handle any errors that may have occurred 
                                // on the server that would cause the rollback to fail, such as 
                                // a closed connection.
                                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                                Console.WriteLine("  Message: {0}", ex2.Message);
                            }
                        }

                    }
                    //  conn.Close();

                }
                catch
                {
                    res = "Number format not valid";
                }
            }
            //send response for user
            Response.Expires = -1;		//required to keep the page from being cached on the                                            client's browser
            Response.ContentType = "text/plain";
            Response.Write(res);
            Response.End();
        }
    }
}